from pyecharts.charts import Timeline, Bar
from pyecharts.globals import ThemeType
from pyecharts.options import TitleOpts, LabelOpts

"""
处理数据
"""

fr = open("1960-2019全球GDP数据.csv", "r", encoding="GB2312")
lines = fr.readlines()
fr.close()
lines.pop(0)  # 删除第一行
data_dict = {}  # 定义空字典 将数据转换为字典存储
for line in lines:
    year = int(line.split(",")[0])
    country = line.split(",")[1]
    GDP = float(line.split(",")[2])
    try:
        data_dict[year].append((country, GDP))
    except KeyError:
        data_dict[year] = []
        data_dict[year].append((country, GDP))
# 准备时间线
sorted_year_list = sorted(data_dict.keys())  # 将字典中的 key 值取出并排序
timeline = Timeline({"theme": ThemeType.LIGHT})  # 创建时间线并设置主题
for year in sorted_year_list:
    # 将年份由大到小排序
    data_dict[year].sort(key=lambda element: element[1], reverse=True)
    # 取出前八名进行展示
    year_data = data_dict[year][0:8]
    countrys = []
    GDPs = []
    for country_gdp in year_data:
        countrys.append(country_gdp[0])
        GDPs.append(country_gdp[1] / 100000000)
    bar = Bar()  # 创建柱状图对象
    countrys.reverse()  # 反转国家让排名靠前的先展示
    GDPs.reverse()
    # 设置标题
    bar.set_global_opts(title_opts=TitleOpts(title=f"{year} 年全球GDP前八国家"))
    bar.add_xaxis(countrys)
    bar.add_yaxis("GDP/亿", GDPs, label_opts=LabelOpts(position="right"))
    bar.reversal_axis()
    timeline.add(bar, str(year))
# 设置自动播放
timeline.add_schema(
    play_interval=500,
    is_timeline_show=True,
    is_auto_play=True,
    is_loop_play=True
)
#  绘图
timeline.render("1960-2019 全球GDP前八国家.html")

# 关闭文件
fr.close()
